package com.ilink.groundservice.service.impl.model;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ilink.groundservice.entity.PO.model.ModelLangflow;
import com.ilink.groundservice.entity.VO.model.ModelInformationResponse;
import com.ilink.groundservice.mapper.model.ModelLangflowMapper;
import com.ilink.groundservice.service.model.ModelLangflowService;
import com.ilink.ilinkapi.dto.ground.model.ModelMetadataRequest;
import com.ilink.groundservice.entity.PO.model.ModelTags;
import com.ilink.groundservice.entity.VO.model.ModelHomepageResponse;
import com.ilink.groundservice.mapper.model.ModelTagsMapper;
import com.ilink.groundservice.service.model.ModelTagsService;
import com.ilink.ilinkcommon.service.oss.OssService;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
* @author LENOVO
* @description 针对表【model_metadata】的数据库操作Service实现
* @createDate 2024-09-16 18:56:40
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class ModelLangflowServiceImpl  extends ServiceImpl<ModelLangflowMapper, ModelLangflow>
    implements ModelLangflowService {
    private final ModelLangflowMapper modelLangflowMapper;
    private final ModelTagsService modelTagsService;
    private final ModelTagsMapper modelTagsMapper;
    private final OssService ossService;

    /**
     * @Author ZhangBo
     * @Description 分页查询模型广场元数据
     * @Date 17:01 2024/9/17
     * @Param [request]
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.ilink.groundservice.entity.VO.model.ModelHomepageResponse>
     **/
    @Override
    public IPage<ModelHomepageResponse> getModelMetadata(ModelMetadataRequest request) {
        try{
            int page = request.getPage();
            int size = request.getSize();
            String keywords = request.getKeywords();
            String tag = request.getTag();
            System.out.println("模型广场元数据");
            System.out.println(keywords);

            LambdaQueryWrapper<ModelLangflow> queryWrapper = new LambdaQueryWrapper<>();

            // 根据传入的关键词和标签条件，构建查询条件（注意空的判断）
            if (keywords != null && !keywords.isEmpty()) {
                // 查询匹配关键词的模型 ID 列表
                List<Long> matchingModelIds = modelTagsService.list(
                    new LambdaQueryWrapper<ModelTags>().like(ModelTags::getTag, keywords)
                ).stream().map(ModelTags::getModelId).collect(Collectors.toList());

                // 构建查询条件，匹配模型名称或描述
                queryWrapper.and(wrapper -> {
                    wrapper.like(ModelLangflow::getModelName, keywords)
                        .or()
                        .like(ModelLangflow::getDescription, keywords)
                        .or()
                        .like(ModelLangflow::getBelong,keywords);

                    // 如果存在匹配的模型 ID，则将其加入 in 查询条件
                    if (!matchingModelIds.isEmpty()) {
                        wrapper.or().in(ModelLangflow::getModelId, matchingModelIds);
                    }
                });
            }

            // 根据标签构建查询条件
            if (tag != null && !tag.isEmpty()) {
                // 查询出包含该标签的模型 ID 列表
                List<Long> modelIds = modelTagsService.list(
                    new LambdaQueryWrapper<ModelTags>().eq(ModelTags::getTag, tag)
                ).stream().map(ModelTags::getModelId).collect(Collectors.toList());

                if (!modelIds.isEmpty()) {
                    queryWrapper.in(ModelLangflow::getModelId, modelIds);
                } else {
                    // 如果没有匹配的 modelId，则返回空分页
                    return new Page<>();
                }
            }

            // 执行分页查询
            IPage<ModelLangflow> modelPage = this.page(new Page<>(page, size),
                queryWrapper);;

            // 转换结果到 ModelHomepageResponse
            List<ModelHomepageResponse> modelHomepageResponses = modelPage.getRecords().stream()
                .map(model -> {
                    ModelHomepageResponse response = new ModelHomepageResponse();
                String name = model.getModelName();

                List<String> tags = modelTagsService.list(
                    new LambdaQueryWrapper<ModelTags>().eq(ModelTags::getModelId,
                        model.getModelId())
                ).stream().map(ModelTags::getTag).collect(Collectors.toList());
                response.setTags(tags);

                String url = ossService.getIconUrl("dataset-square-migrate", "model_icon/" + name);
                log.info("生成icon URL模型 {}: {}", name, url);

                response.setModelId(model.getModelId());
                response.setModelName(model.getModelName());
                response.setModelLabel(model.getModelLabel());
                response.setDescription(model.getDescription());
                response.setIconUrl(url);
                return response;
            }).collect(Collectors.toList());

            Page<ModelHomepageResponse> modelHomepageResponsePage = new Page<>(page, size);
            modelHomepageResponsePage.setRecords(modelHomepageResponses);
            modelHomepageResponsePage.setTotal(modelPage.getTotal());
            modelHomepageResponsePage.setCurrent(modelPage.getCurrent());
            modelHomepageResponsePage.setSize(modelPage.getSize());
            return modelHomepageResponsePage;
        }catch (Exception e){
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 查询模型广场详情数据
     * @Date 21:08 2024/9/17
     * @Param [targetId]
     * @return com.ilink.groundservice.entity.VO.model.ModelInformationResponse
     **/
    @Override
    public ModelInformationResponse getModelInformation(Long targetId) {
        try{
            // 使用 LambdaQueryWrapper 查询 metadata
            LambdaQueryWrapper<ModelLangflow> metadataQuery = new LambdaQueryWrapper<>();
            metadataQuery.eq(ModelLangflow::getModelId, targetId);
            ModelLangflow metadata = modelLangflowMapper.selectOne(metadataQuery);

            if (metadata == null) {
                // 处理未找到的情况，可以抛出异常或返回 null
               log.error("指定模型信息未找到");
               return null;
            }

            // 查询 tags
            LambdaQueryWrapper<ModelTags> tagsQuery = new LambdaQueryWrapper<>();
            tagsQuery.eq(ModelTags::getModelId, targetId);
            List<ModelTags> tagsList = modelTagsMapper.selectList(tagsQuery);

            // 使用流将 tags 转换为列表
            List<String> tags = tagsList.stream()
                .map(ModelTags::getTag)
                .collect(Collectors.toList());

            String name = metadata.getModelName();
            String url = ossService.getIconUrl("dataset-square-migrate", "model_icon/" + name);
            log.info("生成icon URL for model {}: {}", name, url);

            // 构建响应
            ModelInformationResponse response = new ModelInformationResponse();
            response.setModelId(metadata.getModelId());
            response.setModelName(metadata.getModelName());
            response.setTags(tags);
            response.setIconUrl(url);
            response.setVersionId(metadata.getVersionId());
            response.setVersionNum(metadata.getVersionNum());
            response.setDescription(metadata.getDescription());
            response.setDisclaimer(metadata.getDisclaimer());

            return response;
        }catch (Exception e){
            log.error("函数getModelInformation报错"+e);
            return null;
        }
    }
}




